<template>
	<a-modal v-bind="options">
		<a-typography-paragraph>
			<a-typography-text type="danger" v-if="prencet === -1">{{ exception || '数据导出异常，请联系管理员' }}</a-typography-text>
			<template v-else-if="prencet < 100">数据正在导出，请耐心等候</template>
			<template v-else>
				导出完成，共计导出 {{ exportData.count }} 条数据！点击下载：
				<a :href="exportData.url" target="_blank">{{ exportData.name }}</a>
			</template>
		</a-typography-paragraph>
		<a-progress :percent="prencet" :status="prencet === -1 ? 'exception' : 'success'" />
	</a-modal>
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, watchEffect} from 'vue'

	const props = defineProps<{
		// 导出数据接口api方法
		action: Function
		// 导出数据参数
		params: any
		visible: boolean
	}>()

	const timer = ref()
	const prencet = ref<number>(0)
	const exception = ref<string | null>()
	const exportData = ref<{
		count?: 0
		name?: null
		url?: null
	}>({})

	const emits = defineEmits(['update:visible'])
	const options = reactive({
		title: '导出',
		footer: null,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			exception.value = null
			clearInterval(timer.value)
			emits('update:visible', false)
		}
	})

	watchEffect(() => {
		if (props.visible) {
			prencet.value = 0

			timer.value = setInterval(() => {
				if (prencet.value < 99) {
					prencet.value++
				}
			}, 1000)

			props
				.action(props.params)
				.then(({data}: any) => {
					prencet.value = 100
					exportData.value = data
				})
				.catch(({data}: any) => {
					prencet.value = -1
					exception.value = data.msg
				})
				.finally(() => clearInterval(timer.value))
		}
	})
</script>
